﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fadd.InversionOfControl;
using Fadd.Messaging;
using Xunit;

namespace Fadd.Test.Messaging
{
    public class BrokerTest : ISubscriberOf<TestMessage1>, ISubscriberOf<TestMessage2>
	{
		private MessageBroker _broker;
		private TestMessage1 _testMsg1;
		private IMessage _receivedMessage;
	    private bool _throw = false;
        private LightWeightIoc _ioc = new LightWeightIoc();

		public BrokerTest()
		{
            _broker = new MessageBroker(_ioc);

		}

		[Fact]
		public void Subscription()
		{
			_testMsg1 = new TestMessage1();
			_broker.Publish(_testMsg1);
			Assert.Same(_testMsg1, _receivedMessage);
		}

        [Fact]
        public void ExceptionPolicyBreak()
        {
            _testMsg1 = new TestMessage1();
            _throw = true;
            Assert.Throws(typeof (InvalidOperationException), () => _broker.Publish(_testMsg1));
        }

        [Fact]
        public void ExceptionPolicyLog()
        {
            _broker = new MessageBroker(_ioc);
            _testMsg1 = new TestMessage1();
            _throw = true;
            _broker.Publish(_testMsg1);
        }


        [Fact]
        public void SubscribePublishUnsubscribePublish()
        {
            _testMsg1 = new TestMessage1();
            _broker.Publish(_testMsg1);
            Assert.Same(_testMsg1, _receivedMessage);
            _receivedMessage = null;
            _broker.Publish(_testMsg1);
            Assert.Null(_receivedMessage);
        }


		/// <summary>
		/// Consume a message
		/// </summary>
		/// <param name="message">Message to consume</param>
		public void Consume(TestMessage1 message)
		{
            if(_throw)
                throw new InvalidOperationException("So you want an exception, uhu?");
			_receivedMessage = message;
		}

		/// <summary>
		/// Consume a message from the <see cref="IMessageBroker"/>
		/// </summary>
		/// <param name="message">Message to consume</param>
		public void Consume(TestMessage2 message)
		{
			_receivedMessage = message;
		}

        public void ProcessMessage(TestMessage1 message)
        {
            throw new NotImplementedException();
        }

        public void ProcessMessage(TestMessage2 message)
        {
            throw new NotImplementedException();
        }
	}
}
